package com.hunan.api.catv.service.biz.function.remote;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.google.gson.JsonObject;
import com.hunan.api.catv.common.Constants;
import com.hunan.api.catv.common.ConstantsMsg;
import com.hunan.api.catv.entity.ServiceResult;
import com.hunan.api.catv.entity.po.MemberAccountRelated;
import com.hunan.api.catv.entity.vo.MemberVo;
import com.hunan.api.catv.service.ResultService;
import com.hunan.api.catv.service.biz.member.MemberBiz;
import com.hunan.api.catv.service.biz.system.SystemDictBiz;
import com.hunan.api.catv.service.impl.function.remote.RemoteControlService;
import com.hunan.api.catv.utils.GsonUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;

/**
 * @author wangchao
 * @date 2021-04-26 10:17 上午
 */
@Service
public class RemoteControlBiz extends ResultService {

    public static Logger log = LoggerFactory.getLogger(RemoteControlBiz.class);

    @Autowired
    RemoteControlService remoteControlService;

    @Autowired
    MemberBiz memberBiz;

    @Autowired
    SystemDictBiz systemDictBiz;

    /**
     * 遥控器功能
     */
    public ServiceResult remoteControl(Integer memberId, String keyCode) {
        MemberVo info = memberBiz.info(memberId);
        if (info == null) {
            return buildFail(ConstantsMsg.NOT_YET_MEMBER);
        }
        String key = systemDictBiz.getStringByKey(Constants.remote_control_config);
        JsonObject jsonObject = GsonUtils.fromJson(key, JsonObject.class);
        String domain = jsonObject.get("domain").getAsString();
        String appId = jsonObject.get("appId").getAsString();
        String secretKey = jsonObject.get("secretKey").getAsString();
        //获取服务商遥控器token
        String accessToken = getAccessToken(domain, appId, secretKey);
        if (accessToken == null) {
            return buildFail(ConstantsMsg.third_party_error);
        }
        //查询该用户是否绑定大屏账号
        MemberAccountRelated memberAccountRelated = new MemberAccountRelated().selectOne(new QueryWrapper<MemberAccountRelated>().eq(MemberAccountRelated.MEMBER_ID, memberId)
                .eq(MemberAccountRelated.TYPE, 2).eq(MemberAccountRelated.STATUS, 1));
        if (memberAccountRelated == null) {
            return buildFail(ConstantsMsg.NOT_YET_BIND_CARD);
        }
        //查询用户是否绑定
        JsonObject bindJson = bindEquipment(domain, info.getPhone(), memberAccountRelated.getAccountId(), accessToken, memberAccountRelated.getMac(), memberAccountRelated.getTerminalType());
        if (bindJson == null) {
            return buildFail(ConstantsMsg.third_party_error);
        }
        //调用遥控指令
        JsonObject remoteJson = invokeRemote(domain, accessToken, info.getPhone(), memberAccountRelated.getAccountId(), keyCode);
        ServiceResult serviceResult = buidFailResult(remoteJson);
        if (serviceResult != null) {
            return serviceResult;
        }
        return buildOK(remoteJson);
    }

    private ServiceResult buidFailResult(JsonObject jsonObject) {
        if (jsonObject == null) {
            return buildFail(ConstantsMsg.third_party_error);
        }
        if (jsonObject.get("code").getAsInt() != 200) {
            return buildFail(jsonObject.get("message").getAsString());
        }
        return null;
    }

    private String getAccessToken(String domain, String appId, String secretKey) {
        HashMap<String, String> map = new HashMap<>(16);
        map.put("appId", appId);
        map.put("secretKey", secretKey);
        String accessToken = remoteControlService.getAccessToken(domain, map);
        return accessToken;
    }

    private JsonObject bindEquipment(String domain, String phone, String accountId, String accessToken, String mac, int deviceType) {
        //查询用户是否绑定
        JsonObject jsonObject = null;
        try {
            jsonObject = remoteControlService.getBindEquipmentByUserPhone(domain, accessToken, phone);
            if (jsonObject != null) {
                return jsonObject;
            }
            //未绑定进行绑定
            HashMap<String, String> map = new HashMap<>(16);
            map.put("boxId", accountId);
            map.put("mac", mac);
            //deviceType 1（DVB 盒子）2（IP 盒子）---> terminalType 0：DVB 1：IP
            map.put("deviceType", String.valueOf(deviceType + 1));
            map.put("userId", phone);
            return remoteControlService.bindEquipment(domain, map, accessToken);
        } catch (Exception e) {
            log.error("查询设备绑定失败：{},手机号:{}", accountId, phone);
        }
        return null;
    }

    private JsonObject invokeRemote(String domain, String accessToken, String phone, String accountId, String keyCode) {
        HashMap<String, String> map = new HashMap<>(16);
        map.put("boxId", accountId);
        map.put("keyCode", keyCode);
        map.put("userId", phone);
        return remoteControlService.controlPushByCode(domain, map, accessToken);
    }

}
